Introduction to R Shiny Package

Hakan Turgay & Bertan Taylan

Chapter 1

Motivation, Basic R-Shiny Package and Example

Motivation

  • Scientists mostly use R to process their analyzes

  • Presenting/Sharing their findings are usually done in static format

  • Problem : They cannot present additional questions directly

  • Simple idea: Immigrating ratios from a specific region of Turkey due to years and also forecasts about these ratios (e.g. Journalist)

What is Shiny Package?

  • Shiny is an R package that makes it easy to build interactive web applications (apps) straight from R. This lesson will get you started building Shiny apps right away.
  • Build useful web applications with only a few lines of code—no JavaScript required.
  • Shiny applications are automatically “live” in the same way that spreadsheets are live. Outputs change instantly as users modify inputs, without requiring a reload of the browser.
  • Shiny user interfaces can be built entirely using R, or can be written directly in HTML, CSS, and JavaScript for more flexibility.
  • Pre-built output widgets for displaying plots, tables, and printed output of R objects.

Basically


R Shiny = R + interactivity + web made easy

kmeans

Install Shiny Package

If you still haven’t installed the Shiny package, open an R session, connect to the internet, and run

First App in Shiny

Code Output

firstapp

More Example

Chapter 2

Structure of a Shiny App

Main Structure

  • ui: Nested R functions that assemble an HTML user interface for the app

  • server : A function with instructions on how to build and rebuild the R objects displayed in the UI

  • shinyApp : Combines ui and server into a functioning app

  • Save the template as app.R

  • a call to the shinyApp function

Alternative Approach

kmeans

Say Hello with Shiny

Code Output

helloshiny

Chapter 3

Inputs and Outputs

Input and Project Template

  • Basically, inputs are values which are provided by users. We will try to get this value from UI with components of R-Shiny and with these information, we are going to create an “output” from server side. After that we will try to trigger something on UI with this output.
  • First, we will start with one of the R Shiny’s templates.

Define Input Component

  • Let’s form an input component. We chose radioButtons component for this explanation.

and More Input Component

Input Types

Input Syntax

Input syntax

Define Output

  • Our aim on this example is printing university logo on specific location on UI according to information was retrieved with input.

and More Output Options

  • Different output options can be seen from this table:

Output types

Define Render on Server Side

  • Now we will read the input value and update output area with render function on server side.

and More Render Method Examples

render

Overview UI

res

Overview Server

res

Code Output

  • As result, we retrieved a selection of a university from UI and we passed this information to imageRender function to print the university’s logo again on UI.
res

Chapter 4

Using Checkbox in Shiny

Reviewing an Example

kmeans

Starting to Code Analysis

kmeans

Change code

Result

check

Chapter 5

Improving the Design

Design Part

  • Assemble UI with HTML/CSS/…

  • Adjustment of the layout scheme

Grid Layout

  • This feature is a component of content part.
  • Rows are created by the fluidRow() function and columns defined by the column() function.
  • First parameter of column function is its width (which can take values between 1 and 12).
  • grid

Tabsets

  • Tabsets are good alternatives in need of subdividing the user interface into discrete sections and are components of content part.
  • tabsetPanel function can be used for creating Tabsets.
  • tabset

Chapter 6

Implementations in Shiny: JavaScript, HTML and CSS

Using HTML in R Shiny


In R, HTML elements can be defined by tags keyword.

…and more Html Tag

html tag

External file import (html, css , js ext)

Method of importing depends on type of the file;

To include a CSS file


use includeCSS() or
1. Place the file in the www subdirectory
2. Link to it with:

To include JavaScript


use includeScript() or
1. Place the file in the www subdirectory
2. Link to it with:

To include HTML file

Example of Including Javascript

javascript

Result

kmeans

Chapter 7

Introduction to HTMLWidgets Package

Overview

  • This package builds a framework for creating R bindings to JavaScript libraries. HTMLWidgets can be
    • Used at the R console for data analysis
    • Embedded within R Markdown documents
    • Incorporated into Shiny web applications

Creating a Widget

  • Three elements forms the widget:

    • Dependencies : JavaScript and CSS assets will be used by the widget
    • R binding : This is the function where R stuff happens
    • JavaScript binding : JavaScript code that connects everything and passes the data and the choices collected from the R binding to the JavaScript library which is (are) using in widget

Some most-used HTMLWidget Examples

kmeans


leaflet

kmeans


dygraph

Small Case Study: Predicted Deaths From Lung Disease By Using Dygraph Package

UI part of the code:

Server part of the code

Result

check

Creating a widget step-by-step

Requirements

  • In order to create a new widget, first we have to install htmlwidgets package. To install it from R console;

Scaffolding

To create a new widget you can call the scaffoldWidget function to generate the basic structure for your widget. This function will:

  • Create the .R, .js, and .yaml files required for your widget
  • Tip: If provided, take a Bower package (which is a package manager for web) name and automatically download the JavaScript library (and its dependencies) and add the required entries to the .yaml file. This method is highly preferrable because it guarantees that you get started with the right file structure.

MyWidget

We want to create a widget named ‘mywidget’ in a new package of the same name:

  • This creates a simple widget that takes a single text argument and displays that text within the widgets HTML element. You can try it like this:
  • This is the most minimal widget possible and doesn’t yet include a JavaScript library.

Chapter 8

Publishing Project

Keeping Project in Github

  • Because of their dynamic structure, projects created with R Shiny need platforms which can run R codes. This means, by its nature, extra costs.

  • If we choose to keep our project on a specific location and provide the ability of running the project on users’ locals, first we have to put our project to Github (it must definitely have app.r or server.R files) and guide the users to run these codes on their R console:

Publishing as a Web Site

  • We need a server and a domain to publish our project as a website. There are many paid and considerably less unpaid services to make it happen. Also, R Studio provides following options to its developers:
    • shinyapps.io
    • Shiny Server
    • R Studio Connect

Using shinyapps.io

  • This platform is a paid service, but we have the chance to host one application for free.

  • It is easy to use and works pretty fast.

  • To use this platform, first we have to create user account from this link: https://www.shinyapps.io

  • After logging in, we should get token information from token tab located on up-right corner of the page.

  • Then, we should write token info and following code on our R Shiny projects console panel, respectively:

  • And to deploy:

shinyapp.io From R Studio

  • If we give token properly, now we can share our work with just one click.
check

Using Shiny Server ve R Studio Connect

  • Shiny Server : It is a free project being developed open source. Let’s assume we rented a physical machine (e.g. computers) and we want to run R codes which feed our project. In this case we have to send the Shiny Server’s (R) virtual image to our rented machine.

  • Back-end part of the project can be done by this method, but to create front-end, we will need to purchase a domain (website name).

  • R Studio Connect : is a paid service also developed by R Studio. If we plan to make profits from our applications, we can access some ready to use services by this platform.

Chapter 8

Case Studies

Case Study: Childlessness and Gender Gap By Using Ggraph Package

  • In this section, we will build interactive world maps and show these in the form of an Shiny app.
  • At first, we’re going to start with importing, exploring and cleaning the data that datasets we’re going to use. Since the data sets are dirty, we have to get them in a better shape to make more useful for us.
  • Final forms of our datasets will be like this:

    example

Datasets

example

Creating a function to build map

  • Next, it’s time to define the function that we’ll use for building our world maps. The inputs to this function are the merged data frame, the world data containing geographical coordinates, and the data type, period and indicator the user will select in the R Shiny app.

Function Continues:

Last Step: Building the Shiny App

  • Now we put our data in a good shape and world mapping function ready and specified.
  • Let’s start with UI.

UI Continues with Main Panel:

Server side of the app

Result

example

Case Study: Earthquake Map By Using Leaflet Package

  • screenshot

Distinguishing Depths

Forming the UI

Server part

Creating the Map

Making Checkboxes Dynamic With observe Function

Map Adjustments with Using leafletproxy Function

Result

screenshot

Case Study: Migration By Using Leaflet Package

Using Leaflet

  • For creating a map we used Leaflet library.
  • Leaflet is a open source JavaScript library for creating interactive maps.
  • It can be implemented and used in Shiny easily.
  • Leaflet gives the opportunity of adding informational popups to particular part of maps.
  • leaflet

Result

result